from flask import make_response
from gevent import pywsgi
from Scripts.mq import conn as conn_mq
from Scripts.headers import config, log_format
import logging
import flask
import json


flask_main = flask.Flask(__name__)
logging.basicConfig(level=logging.WARNING, format=log_format)


# 订阅飞书验证所用
def check_feishu(get_data):
    a = dict()
    a["challenge"] = get_data["challenge"]
    resp = make_response(json.dumps(a))
    resp.status = "200"
    resp.headers["Content-Type"] = "application/json"
    return resp


@flask_main.route('/yinge/<some>', methods=['POST'])
def jira_flask(some):
    # 获得所传json格式内容
    get_value = json.loads(flask.request.get_data(as_text=True))

    # 输出flask收到的飞书数据
    logging.warning(f'main,jira_flask接收到数据：{json.dumps(get_value, indent=4, ensure_ascii=False)}')
    try:
        if get_value["challenge"]:
            return check_feishu(get_value)

    except Exception as e:
        if some == 'entry':
            mq_virtual = config.get('mq', 'jira_virtual_host')
            mq_queue = config.get('mq', 'jira_queue')
        elif some == 'wiki':
            mq_virtual = config.get('mq', 'password_virtual_host')
            mq_queue = config.get('mq', 'password_queue')
        elif some == 'select':
            mq_virtual = config.get('mq', 'select_virtual_host')
            mq_queue = config.get('mq', 'select_queue')
        else:
            return 'False'
        # flask获取的post数据
        get_data = flask.request.get_data
        mq = conn_mq(virtual=mq_virtual,
                     user=config.get('mq', 'user'),
                     password=config.get('mq', 'password'),
                     ip=config.get('mq', 'ip'),
                     port=config.get('mq', 'port'))

        # 声明队列，参数为队列名
        mq.queue_declare(queue=mq_queue)
        mq.basic_publish(exchange="", routing_key=mq_queue, body=get_data())
        logging.warning(f'未正常获取{e},{mq_queue},{mq_virtual}')
        return 'True'


server = pywsgi.WSGIServer((config.get('flask', 'ip'),
                            int(config.get('flask', 'port'))),
                           flask_main)  # 绑定端口
server.serve_forever()
